package thread.wang_bao_ling.c25;

import java.util.concurrent.*;

/**
 * @Auther: luobiao
 * @Date: 2020/7/20 07:11
 * @Description:
 */
public class CompletionServiceTest {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor =
                Executors.newFixedThreadPool(3);
        // 创建CompletionService
        CompletionService<Integer> cs = new
                ExecutorCompletionService<>(executor);
        // 异步向电商S1询价
        cs.submit(()->{
            sleep(1,TimeUnit.SECONDS);
            return 1;
        });
        // 异步向电商S2询价
        cs.submit(()->{
            sleep(1,TimeUnit.SECONDS);
            return 2;
        });
        // 异步向电商S3询价
        cs.submit(()->{
            sleep(1,TimeUnit.SECONDS);
            return 3;
        });
        // 将询价结果异步保存到数据库
        for (int i=0; i<3; i++) {
            Integer r = cs.take().get();
            System.out.println(r);
            executor.execute(()->{
                sleep(1,TimeUnit.SECONDS);
                System.out.println("询价结果"+r+"保存到数据库");
            });
        }

        //防止在Test直接结束java进程（在main方法中无需做此处理）
    }


     static void sleep(int t, TimeUnit u) {
        try {
            u.sleep(t);
        } catch (InterruptedException e) {
        }
    }
}
